<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');

class Bill extends CI_Controller {
	function __construct(){
		parent::__construct();
		$this->load->library('encrypt');
		$this->load->model('user_model');
		$this->load->model('bill_model');
		$this->load->model('lookup_model');
		$this->load->library('form_validation');
		$this->load->library('email');
	}
	
	public function download(){
		$type = $this->uri->segment(3);
		$id = $this->uri->segment(4);
		$bill = $this->bill_model->get_bill($id);
		$this->load->helper('download');
		$data = file_get_contents(dirname(__FILE__)."/../../".$type."/".$bill[$type]); // 读文件内容
		force_download($bill[$type], $data);
	}
	
	public function history($page = 0) {
		$email = $this->login();
		if($email){
			$data['title'] = 'Bill history';
			
			$user = $this->user_model->get_user_byemail($email);
			$userid = $user?$user['id']:0;
			$this->load->library('pagination');
			$total = $this->bill_model->count_bill(!$this->is_admin()?$userid:'');
			$config = $this->get_page_config('index.php/bill/history/', $total);
			
			$sort = 'createdate';
			$asc = false;
			$offset = $this->uri->segment(3);
			$offset = $offset?$offset:0;
			$data['results'] = $this->bill_model->list_bill(!$this->is_admin()?$userid:'', $sort, $asc, $config['per_page'], $offset);
			$gamelookup = $this->lookup_model->list_lookup(1);
			foreach ($gamelookup as $item){
				$data['gamelookup'][$item['l_code']] = $item['l_value'];
			}
			$data['statuslookup'] = array('P'=>'等待客服充值', 'C'=>'充值成功', 'R'=>'充值失败');
			$data['offset'] = $offset;
			
			$this->pagination->initialize($config); 

			$this->load->view('templates/header', $data);
			$this->load->view('bill/history', $data);
			$this->load->view('templates/footer');
		}else{
			redirect('/');
		}
	}
	
	private function get_page_config($uri, $total){
		$config['base_url'] = base_url().$uri;
		$config['total_rows'] = $total;
		$config['per_page'] = 5; 
		$config['num_links'] = 2; 
		$config['uri_segment'] = 3;
		
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		
		$config['first_link'] = '&lt;&lt;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		
		$config['next_link'] = '&gt;';
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';
		
		$config['prev_link'] = '&lt;';
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		
		$config['last_link'] = '&gt;&gt;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		
		$config['cur_tag_open'] = '<li class="selected"><a href="#">';
		$config['cur_tag_close'] = '</a></li>';
		return $config;
	}

	private function is_admin(){
		return $this->session->userdata['adminflag'];
	}
	
	public function home(){
		$data['title'] = 'Add bill';
		
		$email = $this->login();
		if($email){
			if(!isset($this->session->userdata['currency'])){
				$result = file_get_contents('http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=SGDCNY=X');
	            $currency = explode(",",$result);
	            $currency = array('value'=>$currency[1], 'time'=>getdate());
	            $this->session->set_userdata('currency', $currency);
			}
			if($this->session->userdata['adminflag']){
	        	redirect('/bill/history/0');
	        	return;
	        }
		}else{
			$this->load->view('templates/header', $data);
			$this->load->view('pages/home', $data);
			$this->load->view('templates/footer');
		}
	}
	
	public function login(){
		$email = $this->input->post('email');
		if ($email){
			$this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required');
			if($this->form_validation->run() == TRUE){
				$this->session->set_userdata('user_email', $email);
				$pwd = $this->input->post('password');
				$this->session->set_userdata('adminflag', ($email == "gxw19851218@gmail.com" && $pwd == 'P@$$w0rd'));
			}
		}
		return $this->session->userdata('user_email');
	}
	
	public function detail(){
		if($this->login()){
			$id = $this->uri->segment(3);
			$bill = $this->bill_model->get_bill($id);
			$data['title'] = 'Bill Detail';
			$data['bill'] = $bill;
			$data['gamename'] = $this->lookup_model->get_lookup($bill['account_type']);
			$data['statuslookup'] = array('P'=>'等待客服充值', 'C'=>'充值成功', 'R'=>'充值失败');
			$this->load->view('templates/header', $data);
			$this->load->view('bill/'.($this->is_admin()?'admin_detail':'detail'), $data);
			$this->load->view('templates/footer');
		}else{
			$data = 'Home';
			$this->load->view('templates/header', $data);
			$this->load->view('pages/home', $data);
			$this->load->view('templates/footer');
		}
	}
	
	public function editbill(){
		$this->form_validation->set_rules('cn_money', 'Amount', 'trim|numeric');
		
		$id = $this->input->post('id');
		$cmd = $this->input->post('cmd');
		$upload = $this->upload_receipt('receipt2');
		$arr['status'] = $cmd == '1'?'C':'R';
		if($upload['msg'] == 'success'){
			$arr['receipt2'] = $upload['filename'];
		}
		$arr['cn_money'] = $this->input->post('cn_money');
		$arr['modifydate'] = date("Y-m-d h:i:s");
		$this->bill_model->bill_update($id, $arr);
		$bill = $this->bill_model->get_bill($id);
		
		$data['title'] = 'Bill Detail';
		$data['bill'] = $bill;
		$data['gamename'] = $this->lookup_model->get_lookup($bill['account_type']);
		$data['statuslookup'] = array('P'=>'等待客服充值', 'C'=>'充值成功', 'R'=>'充值失败');
		
		$user = $this->user_model->get_user($bill['user_id']);
		$data['success'] = $cmd == '1'?'充值完成。':'拒绝充值。';
		$this->load->view('templates/header', $data);
		$this->load->view('bill/admin_detail', $data);
		$this->load->view('templates/footer');
		
		$this->email->from('gxw19851218@gmail.com', 'Administrator');
		$this->email->to($user['email']); 
		$this->email->subject('游戏充值成功');
		$this->email->message('游戏名称:'.$data['gamename']['l_value'].'<br>游戏账号:'.$bill['account_no']); 
		$this->email->send();
	}
	
	public function addbill(){
		$this->form_validation->set_rules('account_no', 'Game account', 'trim|required');
		$this->form_validation->set_rules('account_type', 'Game Name', 'trim|required');
		$this->form_validation->set_rules('sg_money', 'Amount', 'trim|required|numeric');
		
		$upload = $this->upload_receipt('receipt1');
		$account_type = $this->input->post('account_type');
		$others = $this->input->post('others');
		
		$success = false;
		$errors = '';
		if($account_type == 'others' && trim($others) == ''){
			$errors = 'Game Name is required.';
		}
		if($upload['msg'] == 'success' & $this->form_validation->run() == TRUE & $errors == ''){
			$email = $this->session->userdata('user_email');
			$user = $this->user_model->get_user_byemail($email);
			if(!$user){
				$this->user_model->user_insert(array('email'=>$email));
				$user = $this->user_model->get_user_byemail($email);
			}
			
			if($account_type == 'others'){
				$rs = $this->lookup_model->get_last_game_code($others);
				$account_type = $rs['l_code'];
				if($rs['operate'] == 'create'){
					$arr = array('l_type'=>1, 'l_code'=>$account_type, 'l_value'=>$others);
					$this->lookup_model->lookup_insert($arr);
				}
			}
			
			$rate = $this->session->userdata['currency']['value'];
			$account_no = $this->input->post('account_no');
			$arr = array(
			'user_id' => $user['id'],
			'status' => 'P',
			'account_no' => $this->input->post('account_no'),
			'account_type' => $account_type,
			'receipt1' => $upload['filename'],
			'sg_money' => $this->input->post('sg_money'),
			'rate' => $this->session->userdata['currency']['value'],
			'createdate'=>date("Y-m-d h:i:s"),
			);
			$this->bill_model->bill_insert($arr);
			$success = '已提交客服，请等待充值。';
			
			$game = $this->lookup_model->get_lookup($account_type);
			
			$this->email->from($email);
			$this->email->to('gxw19851218@gmail.com'); 
			$this->email->subject('游戏充值');
			$this->email->message('游戏名称:'.$game['l_value'].'<br>游戏账号:'.$account_no); 
			$this->email->send();
		}
		
		$data['title'] = 'Add bill';
		$data['success'] = $success;
		$data['errors'] = $errors;
		$data['upload'] = $upload;
		$this->load->view('templates/header', $data);
		$this->load->view('bill/addbill', $data);
		$this->load->view('templates/footer');
	}
	
	private function upload_receipt($name){
		$config['upload_path']="./".$name;
		$config['allowed_types']="gif|jpg|png|jpeg";
		$config['max_size']="20000";
		$this->load->library("upload", $config);
		if($this->upload->do_upload($name)){
			$uploadfile = $this->upload->data();
			return array('msg'=>'success', 'filename'=>$uploadfile['file_name']);
		}
		return array('msg'=>$this->upload->display_errors());
	}
}
